package com.go8.sso.service;

import com.go8.common.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.go8.common.util.UUIDUtils;
import com.go8.sso.mapper.MemberMapper;
import com.go8.sso.pojo.Member;
import com.go8.sso.token.TokenCache;

@Service
public class MemberServiceImpl implements MemberService {
	@Autowired
	private MemberMapper memberMapper;

	@Autowired
	private TokenCache tokenCache; //使用redis代替
	
	/**
	 * 身份认证代码
	 */
	@Override
	public String login(Member member) {
		Member mem = memberMapper.selectByLogin(member);
		if(mem!=null) {
            mem.setPassword(null);
            mem.setLastLoginIp(null);
			//generate token
			String uuid = UUIDUtils.getUUID();
			tokenCache.setByToken(uuid, mem);
			return uuid;
		}else {
			return null;
		}
	}

	@Override
	public void logout(String token) {
		tokenCache.delByToken(token);
	}

	/**
	 * 根据token查询用户信息
	 */
	@Override
	public Member getMemberInfo(String token) {
		Object object = tokenCache.getByToken(token);
		if(object!=null)
			return (Member)object;
		else {
			return null;
		}
	}

	@Override
	public String register(Member member) {
		memberMapper.insertSelective(member);
		//generate token
		String uuid = UUIDUtils.getUUID();
		tokenCache.setByToken(uuid, member);
		return uuid;
	}

	@Override
	public Member validateUnique(Member member) {
		return memberMapper.selectByUnique(member);
	}

}
